package com.passer.simpletransfer.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.passer.simpletransfer.config.SimpleTransferProperties;
import com.passer.simpletransfer.contant.Browser;
import com.passer.simpletransfer.service.BrowserBookmarkService;
import com.passer.toolbox.common.file.util.FileReadUtils;
import com.passer.toolbox.common.file.util.FileWriteUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class BrowserBookmarkServiceImpl implements BrowserBookmarkService {

    private final SimpleTransferProperties properties;

    @Autowired
    public BrowserBookmarkServiceImpl(SimpleTransferProperties properties) {
        this.properties = properties;
    }

    @Override
    public String bookmarkExport(Browser browser) {
        JSONArray jsonArray = switch (browser) {
            case CHROME -> new JSONArray();
            case FIREFOX -> new JSONArray();
            case EDGE -> loadEdgeBookmarks();
            default -> new JSONArray();
        };
        buildWebsiteDirectoryHtml(jsonArray);
        return properties.getStaticPathPattern().replace("**", "") + "websiteDirectory.html";

    }

    private JSONArray loadEdgeBookmarks() {
        JSONObject jsonObject;
        try {
            jsonObject = FileReadUtils.readJsonFile(properties.getBrowserBookmark().get(Browser.EDGE.name()));
        } catch (IOException e) {
            throw new RuntimeException("Edge浏览器收藏夹信息读取失败", e);
        }
        JSONArray jsonArray = new JSONArray();
        JSONArray jsonArrayTemp = new JSONArray();
        JSONObject otherJsonObject = new JSONObject();
        JSONArray otherJsonArray = new JSONArray();
        otherJsonObject.put("category", "其他");
        otherJsonObject.put("sites", otherJsonArray);
        JSONObject roots = jsonObject.getJSONObject("roots");
        jsonArrayTemp.addAll(roots.getJSONObject("bookmark_bar").getJSONArray("children"));
        jsonArrayTemp.addAll(roots.getJSONObject("other").getJSONArray("children"));
        jsonArrayTemp.addAll(roots.getJSONObject("synced").getJSONArray("children"));
        for (int i = 0; i < jsonArrayTemp.size(); i++) {
            JSONObject jsonObject1 = jsonArrayTemp.getJSONObject(i);
            JSONObject jsonObject2 = new JSONObject();
            String type = jsonObject1.getString("type");
            if ("url".equals(type)) {
                jsonObject2.put("name", jsonObject1.getString("name"));
                jsonObject2.put("url", jsonObject1.getString("url"));
                otherJsonArray.add(jsonObject2);
                continue;
            }
            JSONArray jsonArray1 = new JSONArray();
            jsonObject2.put("category", jsonObject1.getString("name"));
            jsonObject2.put("sites", jsonArray1);
            jsonArray.add(jsonObject2);
            loadChildren(jsonObject1.getJSONArray("children"), jsonArray1);
        }
        jsonArray.add(otherJsonObject);
        return jsonArray;
    }

    private void loadChildren(JSONArray children, JSONArray jsonArray) {
        for (int i = 0; i < children.size(); i++) {
            JSONObject jsonObject1 = children.getJSONObject(i);
            String type = jsonObject1.getString("type");
            if ("url".equals(type)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", jsonObject1.getString("name"));
                jsonObject.put("url", jsonObject1.getString("url"));
                jsonArray.add(jsonObject);
                continue;
            }
            loadChildren(jsonObject1.getJSONArray("children"), jsonArray);
        }
    }


    private void buildWebsiteDirectoryHtml(JSONArray jsonArray) {
        String htmlTemplate;
        DefaultResourceLoader defaultResourceLoader = new DefaultResourceLoader();
        Resource resource = defaultResourceLoader.getResource("templates/websiteDirectoryTemplate.html");
        try {
            htmlTemplate = FileReadUtils.readString(resource.getInputStream(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("模板文件读取失败！", e);
            throw new RuntimeException(e.getMessage());
        }
        File folder = new File(properties.getSaveFolderPath());
        if (!folder.exists() && !folder.mkdirs()) {
            throw new RuntimeException(folder.getAbsolutePath() + "：文件保存目录不存在");
        }
        File file = new File(folder, "websiteDirectory.html");
        Matcher matcher = Pattern.compile("<script id=\"site-data\">.*?</script>", Pattern.DOTALL).matcher(htmlTemplate);
        htmlTemplate = matcher.replaceFirst("<script id=\"site-data\">const siteData = " + jsonArray + ";</script>");
        try {
            FileWriteUtils.writeFileByString(file.getPath(), htmlTemplate);
        } catch (IOException e) {
            log.error("websiteDirectory.html 文件写入失败", e);
            throw new RuntimeException(e.getMessage());
        }
    }
}
